package com.tkjt.pms.calc.loader.impl;

import java.util.*;

import com.tkjt.pms.common.entity.*;
import com.tkjt.pms.common.utils.DoubleUtil;
import com.tkjt.pms.modules.common.mapper.TkDepartGroupMapper;
import com.tkjt.pms.modules.common.mapper.TkIndexInfoMapper;
import com.tkjt.pms.modules.common.mapper.TkIndexValueAttrsMapper;
import com.tkjt.pms.modules.common.service.TkDepartGroupService;
import com.tkjt.pms.modules.manageWeight.mapper.WeightMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tkjt.pms.calc.common.IndexCalcParallel;
import com.tkjt.pms.calc.formula.common.FormulaConsts;
import com.tkjt.pms.calc.formula.common.FormulaRule;
import com.tkjt.pms.calc.formula.common.FormulaValue;
import com.tkjt.pms.calc.loader.FormulaDataLoader;
import com.tkjt.pms.calc.utils.EsCalcUtils;
import com.tkjt.pms.common.utils.EsJsonUtils;
import com.tkjt.pms.modules.common.mapper.TkIndexValueMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class FormulaDataLoaderImpl implements FormulaDataLoader {

	@Autowired
	private TkIndexValueMapper tkIndexValueMapper;
	@Autowired
	private TkIndexValueAttrsMapper tkIndexValueAttrsMapper;
	@Autowired
	private TkDepartGroupMapper tkDepartGroupMapper;
	@Autowired
	private TkIndexInfoMapper tkIndexInfoMapper;
	@Autowired
	private WeightMapper weightMapper;
	
	
	public Set<String> parseFormulaRule(String formula) {
		Set<String> ruleVariables = new HashSet<>();
		for (String oneVarKey : FormulaConsts.formulaVariableKeys) {
			Set<String> oneResults = EsCalcUtils.searchOneVariableKey(oneVarKey, formula);
			if (!oneResults.isEmpty()) {
				ruleVariables.addAll(oneResults);
			}
		}
		return ruleVariables;
	}

	/***************************************************************************************************************************************
	 * *加载公式中变量的数据，所有列数据：累计列、月份列、季度列
	 */
	@Override
	public FormulaValue doLoader(FormulaRule formulaRule, IndexCalcParallel indexCalcParallel) {

		log.info("start loader formula data...");
		
		FormulaValue formulaValue = new FormulaValue();
		
		Set<String> formulaVariables = this.parseFormulaRule(formulaRule.getFormula());
		for (String variable : formulaVariables) {
			List<Double> variablesData = this.loadVariableData(variable, indexCalcParallel);
			formulaValue.addValue(variable, variablesData);
		}

		return formulaValue;

	}

	/****************************************************
	 * *@variable格式：
	 1）Mi 之类 【没有@数据项，没有@部门，没有@ATR(其实也是部门类别)】
	 2）Mi@数据项 之类【只有@数据项】
	 3）Mi@部门  之类 【只有@部门】
	 4）Mi@数据项@部门 之类
	 5）Mi@ATR  之类 【只有@ATR】
	 6）Mi@数据项@ATR  之类
	 */
	private List<Double> loadVariableData(String variable, IndexCalcParallel indexCalcParallel) {

		List<Double> results = new ArrayList<Double>();

		String calcIndexValueCode = indexCalcParallel.getIndexValueCode();
		String calcIndexDepart = indexCalcParallel.getIndexDepart();
		String indexScorner = indexCalcParallel.getIndexScorer();
		String indexYearMonth = indexCalcParallel.getIndexYearMonth();
		String weight = "";
		String[] tempArray = variable.split("@");
		for(int i = 0 ; i < tempArray.length ; i++ ){
			if(tempArray[i].startsWith("KGI") || tempArray[i].startsWith("KCI")){
				calcIndexValueCode = tempArray[i];
			}
			if (tempArray[i].startsWith("ATR")) {
				calcIndexDepart = getSameGroupDepart(tempArray[i],calcIndexDepart);
				indexScorner = "";

			}
			if (tempArray[i].startsWith("A01A01")) {
				calcIndexDepart = tempArray[i];
				indexScorner = "";
			}
			if (tempArray[i].startsWith("W")) {
				weight = "W";
			}
		}
		/*if (tempArray.length >= 2) {
			if (tempArray[1].startsWith("KGI") || tempArray[1].startsWith("KCI")) {
				calcIndexValueCode = tempArray[1];
			}
			if (tempArray[1].startsWith("A")) {
				calcIndexDepart = getSameGroupDepart(tempArray[1],calcIndexDepart);
			}
		}
		if (tempArray.length >= 3) {
			if (tempArray[1].startsWith("KGI") || tempArray[1].startsWith("KCI")) {
				calcIndexValueCode = tempArray[1];
			} else if (tempArray[2].startsWith("KGI") || tempArray[2].startsWith("KCI")) {
				calcIndexValueCode = tempArray[2];
			}
			if (tempArray[1].startsWith("A") || tempArray[1].startsWith("A")) {
				calcIndexDepart = getSameGroupDepart(tempArray[1],calcIndexDepart);
			} else if (tempArray[2].startsWith("A") || tempArray[2].startsWith("A")) {
				calcIndexDepart = getSameGroupDepart(tempArray[2],calcIndexDepart);
			}
		}*/
		if(StringUtils.isNotEmpty(weight)){
			QueryWrapper<TkIndexValueAttrs> attrQuery = new QueryWrapper<>();
			attrQuery.lambda().eq(TkIndexValueAttrs::getIndexValueCode,calcIndexValueCode);
			attrQuery.lambda().eq(TkIndexValueAttrs::getAttrCode,"orgGroup");
			TkIndexValueAttrs tkIndexValueAttrs = tkIndexValueAttrsMapper.selectOne(attrQuery);
			QueryWrapper<TkIndexInfo> infoQuery = new QueryWrapper<>();
			infoQuery.lambda().eq(TkIndexInfo::getIndexValueCode,calcIndexValueCode);
			TkIndexInfo tkIndexInfo = tkIndexInfoMapper.selectOne(infoQuery);
			QueryWrapper<TkIndexWeight> weightQuery = new QueryWrapper<>();
			weightQuery.lambda().eq(TkIndexWeight::getIndexGroup,tkIndexValueAttrs.getAttrValue().equals("C")?"2":"1");
			weightQuery.lambda().eq(TkIndexWeight::getOrgCode,calcIndexDepart);
			weightQuery.lambda().eq(TkIndexWeight::getIndexCode,tkIndexInfo.getIndexCode());
			TkIndexWeight tkIndexWeight = weightMapper.selectOne(weightQuery);
			if (null == tkIndexWeight) {
				tkIndexWeight = new TkIndexWeight();
			}
			Map<String, Object> beanValues = EsJsonUtils.bean2Map(tkIndexWeight);
			if(1== tkIndexWeight.getWeightFormat()){
				String data = beanValues.get("weightM"+indexYearMonth.substring(4)).toString();
				int index = data.indexOf("%");
				data = data.substring(0,index);
				results.add(DoubleUtil.div(Double.valueOf(data),100d));
			}

		}else{
			if(StringUtils.isEmpty(calcIndexDepart)){
				for (String key : FormulaConsts.orderKeys) {
					results.add(0.0d);
				}
				return results;
			}
			QueryWrapper<TkIndexValue> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(TkIndexValue::getIndexValueCode, calcIndexValueCode);
			//特别处理===>重点工作
			if(calcIndexValueCode.startsWith("KGIAAC002") || calcIndexValueCode.startsWith("KCIAAC002")) {
				queryWrapper.lambda().eq(TkIndexValue::getIndexExecutor, "jiqiongxiao");
			}
			queryWrapper.lambda().eq(TkIndexValue::getIndexDepart, calcIndexDepart);
			if(StringUtils.isNotEmpty(indexScorner)){
				queryWrapper.lambda().eq(TkIndexValue::getIndexScorer,indexScorner);
			}
			queryWrapper.lambda().eq(TkIndexValue::getDataType, indexCalcParallel.getDataType());
			List<TkIndexValue> tkIndexValues = tkIndexValueMapper.selectList(queryWrapper);
			TkIndexValue tkIndexValue = new TkIndexValue();
			if (tkIndexValues.size()> 0) {
				tkIndexValue = tkIndexValues.get(0);
			}
			Map<String, Object> beanValues = EsJsonUtils.bean2Map(tkIndexValue);
			for (String key : FormulaConsts.orderKeys) {
				results.add((Double) beanValues.get(key));
			}
		}
		return results;

	}

	public String getSameGroupDepart(String departBiz,String calcIndexDepart){
		QueryWrapper<TkDepartGroup> departGroupQuery = new QueryWrapper<>();
		departGroupQuery.lambda().eq(TkDepartGroup::getIndexDepart,calcIndexDepart);
		TkDepartGroup groupDepart = tkDepartGroupMapper.selectOne(departGroupQuery);
		departGroupQuery = new QueryWrapper<>();
		departGroupQuery.lambda().eq(TkDepartGroup::getDepartGroup,groupDepart.getDepartGroup());
		departGroupQuery.lambda().eq(TkDepartGroup::getDepartBiz,departBiz);
		groupDepart = tkDepartGroupMapper.selectOne(departGroupQuery);
		if(groupDepart != null){
			calcIndexDepart = groupDepart.getIndexDepart();
			return calcIndexDepart;
		}else{
			return "";
		}
	}

}
